import Card from '@/components/Card';
import Tabs, { TabsProps } from '@/components/Tabs';
import { deviceControllerGetDeviceLevelInfo } from '@/services/ess/deviceInfo';
import {
  safetyExecutionControllerGetStackSafetyWorkIndicators,
  safetyExecutionControllerGetStationSafetyWorkIndicators,
} from '@/services/ess/safetyExecution';
import { useModel } from '@@/exports';
import { useIntl } from '@umijs/max';
import { Button, Cascader, DatePicker, Flex, Radio, Space } from 'antd';
import dayjs from 'dayjs';
import quarterOfYear from 'dayjs/plugin/quarterOfYear';
import React, { useEffect, useState } from 'react';
import Stack from './components/Stack';
import StandardDescription from './components/StandardDescription';
import Station from './components/Station';
import styles from './index.less';

type timeArrayType = {
  label: string;
  value: string;
};
dayjs.extend(quarterOfYear);
const SaveEvaluate: React.FC = () => {
  const intl = useIntl();
  const [stationData, setStationData] = useState();
  const [stackData, setStackData] = useState();
  const { initialState } = useModel('@@initialState');
  const [treeData, setTreeData] = useState([]);
  const [bmsVal, setBmsVal] = useState('');
  const [pickerType, setPickerType] = useState('month');
  const [pickerDate, setPickerDate] = useState(dayjs().subtract(1, 'month'));
  const [securitySuggestions, setSecuritySuggestions] = useState();
  const [pickerDateString, setPickerDateString] = useState<string | string[]>(
    dayjs().subtract(1, 'month').format('YYYY-MM'),
  );

  const [stationType, setStationType] = useState('station');
  const timeArray: timeArrayType[] = [
    {
      label: intl.formatMessage({ id: 'batteryVoltage.safe.month' }),
      value: 'month',
    },
    {
      label: intl.formatMessage({ id: 'batteryVoltage.safe.quarter' }),
      value: 'quarter',
    },
    {
      label: intl.formatMessage({ id: 'batteryVoltage.safe.year' }),
      value: 'year',
    },
  ];

  const tabsItems: TabsProps['items'] = [
    {
      key: 'station',
      label: intl.formatMessage({ id: 'batteryVoltage.safe.station' }),
      children: '',
    },
    {
      key: 'stack',
      label: intl.formatMessage({ id: 'batteryVoltage.safe.stack' }),
      children: '',
    },
  ];
  const disabledDate = (current) => {
    return current && current > dayjs().endOf('day');
  };
  const getFormatQuarter = () => {
    const currentDate = dayjs();
    // 获取当前季度
    const currentQuarter = currentDate.quarter();
    // 获取当前年份
    const currentYear = currentDate.year();
    // 计算上一季度的年份和季度
    const previousQuarter = currentQuarter - 1 === 0 ? 4 : currentQuarter - 1;
    const yearOfPreviousQuarter = currentQuarter === 1 ? currentYear - 1 : currentYear;
    return `${yearOfPreviousQuarter}-Q${previousQuarter}`;
  };
  const getBatterStack = () => {
    deviceControllerGetDeviceLevelInfo({ stationId: initialState?.stationId }).then((res) => {
      const combinedTree: API.DeviceInfo[] = [
        ...res?.data?.deviceBoxInfos,
        ...res?.data?.deviceBmsInfos,
      ];
      const nodeMapping = {};
      for (const node of combinedTree) {
        node.children = [];
        nodeMapping[node.id] = node;
      }
      const tree: API.DeviceInfo[] = [];
      combinedTree.forEach((node) => {
        if (node.parentId === 0) {
          tree.push(node);
        } else if (nodeMapping[node.parentId]) {
          nodeMapping[node.parentId].children.push(node);
        }
      });
      setTreeData(tree);
      setBmsVal([tree[0]?.code, tree[0]?.children[0]?.code]);
    });
  };
  const getStationData = () => {
    const params = {
      date: pickerDateString,
      stationId: initialState?.stationId,
    };
    safetyExecutionControllerGetStationSafetyWorkIndicators(params).then((res) => {
      setStationData(res.data);
    });
  };
  const search = (stationType: string, pickerDateString: string) => {
    if (stationType === 'station') {
      const params = {
        date: pickerDateString,
        stationId: initialState?.stationId,
      };
      safetyExecutionControllerGetStationSafetyWorkIndicators(params).then((res) => {
        if (res.success) {
          setStationData(res.data);
          setSecuritySuggestions(res?.data?.securitySuggestions);
        }
      });
    } else {
      const params = {
        bmsCode: bmsVal[1],
        date: pickerDateString,
      };
      safetyExecutionControllerGetStackSafetyWorkIndicators(params).then((res) => {
        if (res.success) {
          setStackData(res.data);
          setSecuritySuggestions(res?.data?.securitySuggestions);
        }
      });
    }
  };

  useEffect(() => {
    getBatterStack();
    getStationData();
  }, []);
  return (
    <>
      <Card>
        <Tabs
          hasHeaderBorder={true}
          defaultActiveKey={'station'}
          items={tabsItems}
          onChange={(e) => {
            setStationType(e);
            search(e, pickerDateString as string);
          }}
          tabsLevel={2}
        ></Tabs>
        <Flex className={styles.headerContent} align={'center'} justify={'space-between'}>
          <Space style={{ marginLeft: '20px' }}>
            <div>{intl.formatMessage({ id: 'batteryVoltage.safe.cycle' })}</div>
            <div>
              <Radio.Group
                onChange={(e) => {
                  setPickerType(e.target.value);
                  setPickerDate(
                    e.target.value === 'month'
                      ? dayjs().subtract(1, 'month')
                      : e.target.value === 'quarter'
                      ? dayjs().subtract(1, 'quarter')
                      : dayjs().subtract(1, 'year'),
                  );
                  setPickerDateString(
                    e.target.value === 'month'
                      ? dayjs().subtract(1, 'month').format('YYYY-MM')
                      : e.target.value === 'quarter'
                      ? getFormatQuarter()
                      : dayjs().subtract(1, 'year').format('YYYY'),
                  );
                  search(
                    stationType,
                    e.target.value === 'month'
                      ? dayjs().subtract(1, 'month').format('YYYY-MM')
                      : e.target.value === 'quarter'
                      ? getFormatQuarter()
                      : dayjs().subtract(1, 'year').format('YYYY'),
                  );
                }}
                value={pickerType}
              >
                {timeArray.map((item) => {
                  return (
                    <Radio key={item.value} value={item.value}>
                      {item.label}
                    </Radio>
                  );
                })}
              </Radio.Group>
            </div>
            <div>
              <DatePicker
                allowClear={false}
                disabledDate={disabledDate}
                picker={pickerType}
                size={'middle'}
                value={pickerDate}
                onChange={(e, dateString) => {
                  setPickerDateString(dateString);
                  setPickerDate(e);
                }}
              ></DatePicker>
            </div>
            {stationType === 'stack' && (
              <Space>
                <span> {intl.formatMessage({ id: 'batteryVoltage.safe.stack' })}</span>
                <Cascader
                  value={bmsVal}
                  style={{ width: 200 }}
                  options={treeData}
                  fieldNames={{
                    label: 'name',
                    value: 'code',
                    children: 'children',
                  }}
                  onChange={(e) => {
                    setBmsVal(e);
                  }}
                ></Cascader>
              </Space>
            )}
            <div>
              <Button
                type={'primary'}
                onClick={() => {
                  search(stationType, pickerDateString as string);
                }}
              >
                {intl.formatMessage({ id: 'batteryVoltage.vol.search' })}
              </Button>
            </div>
          </Space>
          <StandardDescription />
        </Flex>
        <div className={styles.SaveContent}>
          {stationType === 'station' ? (
            <Station stationData={stationData} />
          ) : (
            <Stack stackData={stackData} />
          )}
        </div>
      </Card>
      <Card
        title={intl.formatMessage({ id: 'batteryVoltage.safe.suggestions' })}
        style={{ marginTop: '10px' }}
      >
        {/* TODO*/}
        <div>{securitySuggestions || intl.formatMessage({ id: 'batteryVoltage.none' })}</div>
      </Card>
    </>
  );
};

export default SaveEvaluate;
